#include "virtualserial.h"
#include <python2.7/Python.h>
#include <QDebug>
#include <QProcess>

VirtualSerial::VirtualSerial( const QMap<QString, QString> &dev_map, QObject *parent ) : QObject{ parent }, _dev_map( dev_map )
{
    this->moveToThread( &_thread );
    connect( &_thread, &QThread::started, this, &VirtualSerial::doSomething, Qt::DirectConnection );
    _thread.start();
}

VirtualSerial::~VirtualSerial()
{
    _thread.quit();
    _thread.wait();
}

void VirtualSerial::doSomething()
{
    QProcess    process;
    QStringList args = QStringList() << "socat";
    process.execute( "killall socat" );

    Py_Initialize();
    if ( !Py_IsInitialized() ) {
        return;
    }
    PyRun_SimpleString( "import sys" );
    PyRun_SimpleString( "sys.path.append('../serial-simulation')" );

    PyObject *pModule = PyImport_ImportModule( "virtualSerial" );
    if ( !pModule ) {
        qDebug() << "cant open python file";
        return;
    }

    PyObject *pFunRun = PyObject_GetAttrString( pModule, "run" );
    if ( !pFunRun ) {
        qDebug( "get function run failed" );
        return;
    }

    auto *pList = PyList_New( 0 );
    for ( auto it = _dev_map.begin(); it != _dev_map.end(); ++it ) {
        QString name = it.key() + ":" + it.value();
        PyList_Append( pList, Py_BuildValue( "s", name.toLatin1().data() ) );
    }
    PyObject *pArgs = PyTuple_New( 1 );
    PyTuple_SetItem( pArgs, 0, pList );
    auto *pRet = PyEval_CallObject( pFunRun, pArgs );
    Py_DECREF( pRet );

    Py_Finalize();
}
